const {add, query, del} = require('./sqlApi')


/**
 * 获取分享码
 *
 * @param req ?type=$
 *
 *
 *
 * @returns {Promise<void>}
 */
function get(req) {
    let type = req.query.type
    let app = req.query.app || ''

    return new Promise(async resolve => {
        if (app) {
            let rows = await query('codes', `type like "%${app}%"`),arr=[]
            try {
                if (rows) {
                    arr =  rows.map(e=>{
                        console.log(JSON.stringify(e))
                        return e.data
                    })
                }
            } catch (e) {

            }
            resolve(arr)

        } else if (type) {
            let arr = [], num = req.query.num || 3
            let rows = await query('codes', `type="${type}"`)
            try {
                if (rows) {
                    let data = rows[0].data.split('&');
                    num = data.length >= num ? num : data.length - 2
                    let s = new Set(), code;
                    while (s.size < num) {
                        code = Math.floor(Math.random() * data.length)
                        s.add(data[code])
                        data[code] = ''
                        data = data.filter(e => e)
                    }
                    arr = [...s]
                }

            } catch (e) {
                console.log('no data')
            }
            resolve(arr)
        }
    })
}



/**
 *  上传分享码
 *
 * @param req {
 *
 *     obj:{
 *         type#类型
 *         data#分享码 逗号拼接
 *        }
 *
 * }
 * @returns {Promise<string>}
 */
function post(req) {
    let obj = req.payload
    return new Promise(async resolve => {
        await del('codes', `type="${obj.type}"`)
        await add('codes', [obj.type, obj.data, Date.now()])
        resolve('ok')
    })

}

module.exports = {
    get, post
}
